const { find: findOrgUnit } = require('./org-units')
const { list: listRooms } = require('./rooms')
const { list: listUsers } = require('./user')
const Mock = require('mockjs')

const PlayRecords = []
const roomsPage = listRooms(1, 150)
const movieNames = ['一点半', '山上有鬼']
let id = 1
for (let i = 0; i < roomsPage.data.records.length; ++i) {
  const orgUnit = findOrgUnit(roomsPage.data.records[i].orgUnitId)
  const dmPage = listUsers(1, 3, null, orgUnit.id, 'DM', null, null)
  for (let j = 1; j <= dmPage.data.records.length; ++j) {
    PlayRecords.push(Mock.mock({
      id: id++,
      movieName: movieNames[j % movieNames.length],
      movieVersion: '1.6.' + j,
      dmId: dmPage.data.records[j - 1].id,
      dmAccount: dmPage.data.records[j - 1].phoneNumber,
      dmNickname: dmPage.data.records[j - 1].nickname,
      orgUnitName: orgUnit.name,
      orgUnitId: roomsPage.data.records[i].orgUnitId,
      roomId: roomsPage.data.records[i].id,
      roomName: roomsPage.data.records[i].name,
      status: (j % 2) + 1,
      startTime: Mock.Random.datetime(),
      endTime: Mock.Random.datetime(),
      terminator: dmPage.data.records[j - 1].phoneNumber,
      cost: (j - 1) * 45,
      luckyAmount: 5,
      payAmount: (j - 1) * 45 - 5
    }))
  }
}

function list(page, limit, movieName, orgUnitId, userId, roomId) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  roomId = roomId ? parseInt(roomId) : null
  userId = userId ? parseInt(userId) : null
  let mocks = PlayRecords.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    if (roomId && item.roomId !== roomId) return false
    if (userId && item.dmId !== userId) return false
    return !(movieName && (!item.movieName || item.movieName.indexOf(movieName) === -1))
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  return { success: true, data: { total: total, records: mocks }}
}

module.exports = { list }
